/**
 * ______________________________________________________________________________
 *
 * File: MoveCustomerDocs.java
 *______________________________________________________________________________
 *
 * CreatedBy: Verinon
 * CreationDate: Nov 6, 2012   10:36:43 AM   2012
 * Description: This Job read input job parameter based on that list of customer folder move to  destination folder
 *                    Parameter are mandatory, and these parameter should be valid parameters(exist in ECM)
 * 
 *______________________________________________________________________________
 *
 * Copyright: (c) Vietinbank, all rights reserved 
 *______________________________________________________________________________
 *
 *
 *	
	--On Repository	
		Create java method from da 'movecustomerdocsjob' method verb: com.vb.ecm.server.jobs.UpdateUsersFromLOS
        Create job from da 'MoveCustomerDocs'
    
    
    --Description: This Job read input job parameter based on that list of customer folder move to  destination folder
                     Parameter are mandatory, and these parameter should be valid parameters(exist in ECM)
                     
    --Job Name: MoveCustomerDocs
      Job Method name: movecustomerdocsjob
    					
    --job args: -destinationFolderPath /Branch 160/icDoc Docs         ------- Where to Move docs
                -sourceFolderIDs 160-GHTD-2012-642,160-GHTD-2012-643  ------- What Customer Docs
                -- Log location
                
    --job logs: Content Server Machine: E:\Documentum\jboss5.1.0\server\DctmServer_MethodServer\logs\customjobs.log
    					E:\Documentum\jboss5.1.0\server\DctmServer_MethodServer\log\server.log  
 */
package com.vb.ecm.server.jobs;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.Map;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;

import com.documentum.fc.client.DfQuery;
import com.documentum.fc.client.IDfCollection;
import com.documentum.fc.client.IDfFolder;
import com.documentum.fc.client.IDfQuery;
import com.documentum.fc.client.IDfSession;
import com.documentum.fc.common.DfException;
import com.documentum.fc.common.DfId;
import com.documentum.fc.common.DfLogger;
import com.documentum.fc.common.IDfId;
import com.documentum.fc.methodserver.DfMethodArgumentManager;
import com.documentum.fc.methodserver.IDfMethod;
//import com.documentum.server.impl.method.common.SessionManagerManager;
//import com.documentum.server.impl.method.report.IReportWriter;
import com.documentum.server.impl.method.report.ReportFactory;


public class MoveCustomerDocs implements IDfMethod {

	private static final Logger LOGGER = DfLogger.getLogger(MoveCustomerDocs.class);
	private IDfSession session = null;

	private int methodTraceLevel = 0;
	private ResourceBundle rsb = null;
	private String sourceFolderIDs = "100,102";
	private String destinationFolderPath = "/hieunm/101";
    private DfcSessionManager m_sessionManager = new DfcSessionManager ();
    
	@SuppressWarnings("unchecked")
	public int execute(Map args, PrintWriter writer) throws Exception {

		try {
			ReportFactory rf = new ReportFactory();
			IDfId jobId = new DfId(null);
			boolean moveDocs = false;
			session = m_sessionManager.getSession();
			
			System.out.print("Connect successfully !");
			
			rsb = ResourceBundle.getBundle("com.vb.ecm.server.jobs.updateusersconfig");
			
	
			if (isDestinationPathExist(destinationFolderPath)) {
				if (isSourceFolderExist(sourceFolderIDs)) {
					if (isMovingFolderNotExistOnDest(destinationFolderPath, sourceFolderIDs)) {
						moveDocs = moveDocuments(destinationFolderPath, sourceFolderIDs);
						if (moveDocs == true) {
							updateDocuments(destinationFolderPath);
						} else {
                            System.out.print("moveDocs is false !");
						}
					} else {
						System.out.print("isMovingFolderNotExistOnDest false ! ");
					}
				} else {
					System.out.print("SourceFolder is not exists !");
				}
			} else {
				System.out.print("DestinationPath is not exists !");
			}

			// closing print writer
			

		} catch (Exception e) {
			LOGGER.error("Error in Execute Method : ", e.fillInStackTrace());
			e.printStackTrace();
		} finally {
			m_sessionManager.releaseSession(session);
		}
		return 0;
	}

	/**
	 * Method Name : getLOSUsersFromLOSDB Description : This method will execute
	 * query on registered table and return collection object.
	 * 
	 * @param
	 * @throws DfException
	 **/
	private boolean isDestinationPathExist(String destFolderPath) throws DfException {
		// TODO Auto-generated method stub
		boolean isDestFolPathExist = false;
		IDfFolder destFolderObj = (IDfFolder) session.getObjectByPath(destFolderPath);
		if (destFolderObj != null) {
			isDestFolPathExist = true;
		} else {
			isDestFolPathExist = false;
		}
		return isDestFolPathExist;
	}

	/**
	 * Method Name : getLOSUsersFromLOSDB Description : This method will execute
	 * query on registered table and return collection object.
	 * 
	 * @param
	 * @throws DfException
	 **/
	private boolean isSourceFolderExist(String sourFolderID) throws DfException {
		// TODO Auto-generated method stub
		boolean isDestFolIDExist = false;
		IDfFolder sourFolderObj = null;
		int failed = 0;
		String[] folderIds = sourFolderID.split(",");
		for (int i = 0; i < folderIds.length; i++) {
			sourFolderObj = (IDfFolder) session.getObjectByQualification("dm_folder where object_name='" + folderIds[i] + "'");
			if (sourFolderObj != null) {
			
			} else {
			
				failed = failed + 1;
			}
		}
		if (failed == 0) {
			isDestFolIDExist = true;
		} else {
			isDestFolIDExist = false;
		}
		return isDestFolIDExist;
	}

	/**
	 * Method Name : getLOSUsersFromLOSDB Description : This method will execute
	 * query on registered table and return collection object.
	 * 
	 * @param
	 * @throws DfException
	 **/
	private boolean isMovingFolderNotExistOnDest(String destFolderPath, String sourFolderID) throws DfException {
		// TODO Auto-generated method stub
		boolean isFolderNotExist = false;
		IDfFolder destFolderObj = null;
		int failed = 0;
		String[] folderIds = sourFolderID.split(",");
		for (int i = 0; i < folderIds.length; i++) {
			destFolderObj = (IDfFolder) session.getObjectByPath(destFolderPath + "/" + folderIds[i]);
			if (destFolderObj == null) {

			} else {
			
				failed = failed + 1;
			}
		}
		if (failed == 0) {
			isFolderNotExist = true;
		} else {
			isFolderNotExist = false;
		}
		return isFolderNotExist;
	}

	/**
	 * Method Name :
	 * 
	 * 
	 * @param
	 * @throws DfException
	 **/
	private boolean moveDocuments(String destFolderPath, String sourFolderID) throws DfException {
		// TODO Auto-generated method stub
		boolean moveDone = false;
		IDfQuery moveDocsQuery = null;
		IDfCollection moveDocsColl = null;
		String moveDocsQueryS = null;
		String[] folderIds = sourFolderID.split(",");
		// update dm_folder objects move to '/Branch 160/icDoc Docs' where
		// r_object_id='0b01e240800a6fff'
		for (int i = 0; i < folderIds.length; i++) {
			moveDocsQueryS = "update dm_folder(all) objects move to '" + destFolderPath + "' where object_name ='" + folderIds[i] + "'";
			LOGGER.debug("moveDocsQueryS:-" + moveDocsQueryS);
			moveDocsQuery = new DfQuery();
			moveDocsQuery.setDQL(moveDocsQueryS);
			LOGGER.debug("getLoginUserName:-" + session.getLoginUserName());
			
			moveDocsColl = moveDocsQuery.execute(session, IDfQuery.DF_EXEC_QUERY);
			while (moveDocsColl.next()) {
				int numObjectsUpdated = moveDocsColl.getInt("objects_updated");
				if (numObjectsUpdated == 0) {
					moveDone = false;
					
				} else {
					moveDone = true;
				
				}
			}
		}
		return moveDone;
	}

	/**
	 * Method Name :
	 * 
	 * 
	 * @param
	 * @throws DfException
	 **/
	private boolean updateDocuments(String destPath) throws DfException {
		// TODO Auto-generated method stub
		boolean updateDocsDone = false;
		IDfQuery updateDocsQuery = null;
		IDfCollection updateDocsColl = null;
		String updateDocsQueryS = null;
		String branchId = destPath.substring(8, 11);
		String isIcDoc = destPath.substring(12, 22);
		String docType = null;
		if (isIcDoc.equalsIgnoreCase("icDoc Docs")) {
			docType = "vb_icdoc_docs";
		} else {
			docType = "vb_los_docs";
		}
		updateDocsQueryS = "UPDATE " + docType + " OBJECTS SET  branch_number= '" + branchId + "' where FOLDER('" + destPath + "',descend)";
		LOGGER.debug("updateDocsQueryS:-" + updateDocsQueryS);
		updateDocsQuery = new DfQuery();
		updateDocsQuery.setDQL(updateDocsQueryS);
		updateDocsColl = updateDocsQuery.execute(session, IDfQuery.DF_EXEC_QUERY);
		
		while (updateDocsColl.next()) {
			int numObjectsUpdated = updateDocsColl.getInt("objects_updated");
			if (numObjectsUpdated == 0) {
				updateDocsDone = false;
			} else {
				updateDocsDone = true;
			}
		}
		return updateDocsDone;
	}
	
	public static void main(String args[]) throws Exception {
		//TODO: this class to test some functions in ECM ( not use web service )
		LOGGER.debug("Enter move customer docs");
		MoveCustomerDocs mvd = new MoveCustomerDocs();
		mvd.execute(DfMethodArgumentManager.getArgumentsFromCommandLine(args), new PrintWriter(System.out));
		LOGGER.debug("Exit move customer docs");
	}
}
